import { Button, Card, Input, Form, InputNumber, Radio, Select, Modal,Cascader,Spin,Row,Col} from 'antd';
import { connect} from 'umi';
import React, { useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import Contanst from '@/config/contanst';
import { Map,Marker } from 'react-amap';
import Autocomplete from '@/components/AMapAutoComplete';
import db from '@/utils/localstorage';

const FormItem = Form.Item;

const Loading = <div className="example"><Spin /></div>

  /**
   * 默认地图中心点位置
   */
   const defaultPosition={
    longitude: 118.805871,
    latitude: 32.0835
  }
const BasicForm = props => {
  const { submitting, dispatch,currentShop } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = React.useState(false);
  const [modalPosition, setModalPosition] = React.useState({ longitude: '',latitude: ''});

  useEffect(() => {
   if (dispatch) {
      dispatch({
        type: 'cubeShop/fetchShop',
        payload: {
          id:props.match.params.id
        },
      }).then(()=>{
        form.resetFields()
      })
    }
  }, []);

  /**
   * 地图标记事件
   */
  const markerEvents = {
    dragend: (e) => {
      let lng=e.lnglat.lng;
      let lat=e.lnglat.lat;
      setModalPosition({
        longitude: lng,
        latitude: lat
      })
    }
  }

  /**
   * 调整位置后表单地图标记体现
   */
  const positionProps={
    longitude: currentShop.longitude || defaultPosition.longitude,
    latitude: currentShop.dimensions || defaultPosition.latitude
  }
  const pluginProps = {
    
  }
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 7,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 12,
      },
      md: {
        span: 10,
      },
    },
  };
  const submitFormLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 10,
        offset: 7,
      },
    },
  };

  const onFinish = async() => {
    const values = await form.validateFields();
    const { dispatch } = props;
    if(values.addressArr){
      values.provincial=values.addressArr[0]
      values.city=values.addressArr[1]
      values.district=values.addressArr[2]
      delete values.addressArr
    }
    values.longitude=modalPosition.longitude||""
    values.dimensions=modalPosition.latitude||""
    if(currentShop){
      values.id=currentShop.id
    }
    dispatch({
      type: 'cubeShop/update',
      payload: values,
    });
  };

  /**
   * 调整位置
   */
  const changePosition = () =>{
    setModalPosition({
      longitude: currentShop.longitude||defaultPosition.longitude,
      latitude: currentShop.dimensions||defaultPosition.latitude
    })
    setVisible(true)
  }

  /**
   * 输入框选择位置
   */
  const selectfunc = (e) =>{
    if(e.poi.location) {
      setModalPosition({
        longitude: e.poi.location.lng, latitude: e.poi.location.lat
      })
    } 
  }

  /**
   * 确认调整位置
   */
  const handleOk = () =>{
    currentShop.longitude=modalPosition.longitude;
    currentShop.dimensions=modalPosition.latitude;
    if(dispatch){
      dispatch({
        type: 'cubeShop/common',
        payload: {
          currentShop:currentShop
        },
      });
    }
    setVisible(false)
  }

  /**
   * 取消调整位置
   */
  const handleCancel = () =>{
    setVisible(false)
  }
  return (
    <PageHeaderWrapper>
      <Card bordered={false}>
        <Form
          style={{
            marginTop: 8,
          }}
          form={form}
          name="basic"
          initialValues={currentShop}
        >
          <FormItem
            {...formItemLayout}
            label="场馆名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入场馆名称',
              },
            ]}
          >
            <Input placeholder="请输入"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="电话"
            name="telephone"
            rules={[
              {
                required: true,
                message: '请输入电话号码',
              },
            ]}
          >
            <Input placeholder="请输入"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="地址"
            name="addressArr"
            rules={[
              {
                required: true,
                message: '请选择地址',
              },
            ]}
          >
            <Cascader  placeholder="请选择" fieldNames={{ label: 'name', value: 'id', children: 'children' }} options={db.get('areaList')||[]}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            wrapperCol={{ span: 10,offset: 7, }}
            name="address"
          >
            <Input placeholder="请输入场馆地址" addonAfter={ <a type="primary" onClick={changePosition}>调整定位</a>}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            wrapperCol={{ span: 10,offset: 7, }}
            name="address"
          >
            <div style={{height: 200}}>
              <Map amapkey={Contanst.AMapKey} zoom={15} loading={Loading}  center={positionProps} plugins={['ToolBar']}>
                  <Marker position={positionProps} />
              </Map>
            </div>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="状态"
            name="status"
            rules={[
              {
                required: true,
                message: '请选择场馆状态',
              },
            ]}
          >
            <Radio.Group>
                <Radio value="1">
                  正常
                </Radio>
                <Radio value="2">
                  暂停
                </Radio>
              </Radio.Group>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="排序"
            name="orderNum"
            rules={[
              {
                required: true,
                message: '请输入排序',
              },
            ]}
          >
            <InputNumber
              placeholder="请输入"
              min={0}
              max={100}
            />
          </FormItem>
          <FormItem
            {...submitFormLayout}
            style={{
              marginTop: 32,
            }}
          >
            <Button type="primary" onClick={onFinish} loading={submitting}>
             提交
            </Button>
            <Button
              style={{
                marginLeft: 8,
              }}
              onClick={()=>window.history.back()}
            >
              返回
            </Button>
          </FormItem>
        </Form>
        <Modal
            title="提示"
            visible={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            width={600}
          >
             <Row>
             <Col span={24}>
              <div style={{height: 300}} className="myAmap">
                  <Map amapkey={Contanst.AMapKey} loading={Loading}  zoom={15} center={modalPosition} plugins={['ToolBar']}>
                      <Autocomplete options={pluginProps} onSelect={(e)=>selectfunc(e)} modalPosition={modalPosition} placeholder="请输入场馆地址"/>
                      <Marker position={modalPosition} draggable={true} events={markerEvents}/>
                    </Map>
                </div>
             </Col>
             </Row>
          </Modal>
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading,cubeShop }) => ({
  submitting: loading.effects['cubeShop/update'],
  currentShop:cubeShop.currentShop
}))(BasicForm);
